const fs = require("fs")
var buf = new Buffer.alloc(1024)
const stringRandom = require('string-random')
const dbMod = require('./dbMod')

var dir = 'replycontent/'

// 从html目录中读取文件，filename为文件名，callback为读取完成后的回调函数，其参数为文件内容
function readFile (filename, callback) {
  var readstream = fs.createReadStream(dir + filename)
  var str = ''

  readstream.on('data', (chunk) => {
    str += chunk
  })

  readstream.on('end', () => {
    callback(str)
  })

  readstream.on('error', (err) => {
    console.log(err)
  })
}

// 随机生成文件名并存入html目录中，content为回帖内容，callback为保存成功后的回调函数，其参数为文件名
function addFile (content, callback) {
  var filename = stringRandom(32) // 生成长度为16，包含大小写字母和数字的随机字符串
  var written = false
  fs.open(dir + filename, 'wx', function (err, fd) {
    if (err) {
      console.log(err)
      addFile(content, callback)
    }
    else {
      var writestream = fs.createWriteStream(dir + filename)
      writestream.write(content)
      writestream.end()
      writestream.on('finish', () => {
        callback(filename)
      })
      writestream.on('error', (err) => {
        console.log(err)
      })
    }
  })
}

function addreply (userID, postID, isAnnouncement, content, time, callback) {
  var tablename = isAnnouncement == 0 ? 'post' : 'announcement'
  sql1 = 'INSERT INTO reply (replyContent, replyPostID, replyTime, replyUserID, isAnnouncement, replyFloor) VALUES (?,?,?,?,?,0)'
  dbMod.query(sql1, [content, postID, time, userID, isAnnouncement], (result) => {
    var result1 = eval(result)
    var replyID = result1.insertId

    // 获取最大楼层
    sql2 = 'SELECT MAX(replyFloor) AS maxFloor FROM reply WHERE replyPostID=? AND isAnnouncement=?'
    dbMod.query(sql2, [postID, isAnnouncement], (result) => {
      var maxFloor = eval(result)[0].maxFloor
      sql3 = 'UPDATE reply SET replyFloor=? WHERE replyID=?'
      dbMod.query(sql3, [maxFloor + 1, replyID], (result) => {
        var result3 = eval(result)
        var addRepCount = ', postRepCount=postRepCount+1'

        // 更新回复时间和回复数
        sql4 = 'UPDATE ' + tablename + ' SET ' + tablename + 'ReplyTime=?' + (isAnnouncement == 0 ? addRepCount : '') + ' WHERE ' + tablename + 'ID=?'
        dbMod.query(sql4, [time, postID], (result) => {
          var result4 = eval(result)

          callback(replyID)
        })
      })
    })
  })
}

function getreply (postID, isAnnouncement, callback) {
  let sql1 = 'SELECT * FROM reply WHERE replyPostID=? AND isAnnouncement=?'
  dbMod.query(sql1, [postID, isAnnouncement], (result) => {
    var replies = eval(result)
    var tablename = isAnnouncement == 0 ? 'post' : 'announcement'
    let sql2 = 'SELECT * FROM ' + tablename + ' WHERE ' + tablename + 'ID=?'
    dbMod.query(sql2, [postID], (result) => {
      var post = eval(result)[0]
      var partitionID = isAnnouncement == 0 ? post.postPartID : post.announcementPartID
      let sql3 = 'SELECT * FROM `partition` WHERE partitionID=?'
      dbMod.query(sql3, [partitionID], (result) => {
        var partition = eval(result)[0]
        callback(post, replies, partition)
      })
    })
  })
}

function delreply (replyID, callback) {
  let sql1 = 'SELECT * FROM reply WHERE replyID=?'
  dbMod.query(sql1, [replyID], (result) => {
    var filename = eval(result)[0].replyContent
    var postID = eval(result)[0].replyPostID
    var isAnnouncement = eval(result)[0].isAnnouncement

    if (isAnnouncement == 0) {
      let sql2 = 'UPDATE post SET postRepCount=postRepCount-1 WHERE postID=?'
      dbMod.query(sql2, [postID], (result) => {
        var result2 = result
        DELETE()
      })
    }
    else {
      DELETE()
    }

    function DELETE () {
      fs.unlink(dir + filename, (err) => {
        if (err) console.log(err)
        else {
          sql2 = 'DELETE FROM reply WHERE replyID=?'
          dbMod.query(sql2, [replyID], (result) => {
            callback(eval(result))
          })
        }
      })
    }
  })
}

exports.readFile = readFile
exports.addFile = addFile
exports.addreply = addreply
exports.getreply = getreply
exports.delreply = delreply
exports.dir = dir